package com.viewpagertext.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.DownloadMusicDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.R;
import com.viewpagertext.activitys.LocalMusicActivity;
import com.viewpagertext.activitys.PortAllActivity;
import com.viewpagertext.activitys.SongActivity;
import com.viewpagertext.adapters.LocalSongRecAdapter;
import com.viewpagertext.constructor.ListToPlayEvent;
import com.viewpagertext.constructor.Song;
import com.viewpagertext.help.MediaPlayerHelp;
import com.viewpagertext.utils.LoadLocalMusicUtils;
import com.viewpagertext.utils.LoadSongUtils;
import com.viewpagertext.views.MyRoundedImageView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LocalSingleFragment extends Fragment {

    private RecyclerView recyclerView;
    private List<Song> mLocalMusicList;
    private MediaPlayerHelp mMediaPlayerHelp;
    private boolean isPlaying;
    private View view;
    private BottomSheetDialog bottomSheetDialog;
    private String song, singer, album, duration, p, lrc, picPath;
    private long size;
    private MyRoundedImageView localDialogIcon;
    private Bitmap bitmap;
    private LocalSongRecAdapter localSongRecAdapter;
    private DownloadMusicDao downloadMusicDao;
    private StarredSongDao starredSongDao;
    private EditText filterInfo;
    private List<Song> filteredMusicList;

    public LocalSingleFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_local_single, container, false);
        mLocalMusicList = new ArrayList<>();
        filteredMusicList = new ArrayList<>();
        downloadMusicDao = AppDatabase.getInstance().downloadMusicDao();
        starredSongDao = AppDatabase.getInstance().starredSongDao();

        newData();
        initView();
        return view;
    }

    // 更新本地音乐数据
    private void newData() {
        mLocalMusicList.clear();
        mLocalMusicList.addAll(LoadLocalMusicUtils.getMusic());
        filteredMusicList = new ArrayList<>(mLocalMusicList);
    }

    private void initView() {
        recyclerView = view.findViewById(R.id.local_single_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        localSongRecAdapter = new LocalSongRecAdapter(getActivity(), filteredMusicList);
        recyclerView.setAdapter(localSongRecAdapter);

        // 设置item及item中控件的点击事件
        localSongRecAdapter.setOnItemClickListener(MyItemClickListener);
        mMediaPlayerHelp = MediaPlayerHelp.getInstance(getActivity());

        filterInfo = view.findViewById(R.id.filter_info);
        //监听文本内容变化
        filterInfo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String searchText = editable.toString().toLowerCase();
                filteredMusicList.clear(); // 清空现有的过滤列表
                for (Song song : mLocalMusicList) {
                    if (song.song.concat(song.singer).concat(song.album).toLowerCase().contains(searchText)) {
                        filteredMusicList.add(song);
                    }
                }
                localSongRecAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * item＋item里的控件点击监听事件
     */
    private LocalSongRecAdapter.OnItemClickListener MyItemClickListener = new LocalSongRecAdapter.OnItemClickListener() {

        @Override
        public void onItemClick(View v, LocalSongRecAdapter.ViewName viewName, int position) {
            song = filteredMusicList.get(position).song;//获取歌名
            singer = filteredMusicList.get(position).singer;//获取歌手
            size = filteredMusicList.get(position).size;//歌曲大小
            duration = LoadSongUtils.formatTime(filteredMusicList.get(position).duration);//歌曲时长
            album = filteredMusicList.get(position).album;//歌曲专辑
            long albumId = filteredMusicList.get(position).albumId;
            picPath = filteredMusicList.get(position).picPath;
            bitmap = BitmapFactory.decodeFile(picPath);
            p = filteredMusicList.get(position).path;//获得歌曲的地址
            System.out.println("bitmap path" + picPath);
            lrc = filteredMusicList.get(position).lrc;

//            String lrc = mLocalMusicList.get(position).

            //viewName可区分item及item内部控件
            switch (v.getId()) {
                case R.id.localmenu:
//                    Toast.makeText(getActivity(),"你点击了同意按钮"+(position+1),Toast.LENGTH_SHORT).show();
                    initDialog();
                    break;
//                case R.id.btn_refuse:
//                    Toast.makeText(MainActivity.this,"你点击了拒绝按钮"+(position+1),Toast.LENGTH_SHORT).show();
//                    break;
                default:
//                    Toast.makeText(getActivity(),"你点击了item按钮"+(position+1),Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), SongActivity.class);
                    EventBus.getDefault().postSticky(new ListToPlayEvent(picPath, song, singer, lrc, p, duration, ""));
                    System.out.println("song" + song);
                    System.out.println("singer" + singer);
                    System.out.println("lrc" + lrc);
                    System.out.println("p" + p);
                    System.out.println("duration" + duration);
//                    viewPager.setCurrentItem(1);
                    getActivity().startActivity(intent);
                    break;
            }
        }

        @Override
        public void onItemLongClick(View v) {

        }
    };


    private void initDialog() {
        View view = View.inflate(getActivity(), R.layout.local_dialog, null);
        TextView dialog_song = view.findViewById(R.id.dialog_song);//歌名
        dialog_song.setText(song);
        TextView dialog_album = view.findViewById(R.id.dialog_album);//专辑
        dialog_album.setText(album);
        TextView dialog_singer = view.findViewById(R.id.dialog_singer);//歌手
        dialog_singer.setText(singer);
        TextView dialog_singer2 = view.findViewById(R.id.dialog_singer2);//歌手
        dialog_singer2.setText(singer);
        TextView dialog_time = view.findViewById(R.id.dialog_time);//时长
        dialog_time.setText(duration);
        TextView dialog_size = view.findViewById(R.id.dialog_size);//歌曲大小
        dialog_size.setText(((new DecimalFormat("#.00")).format(Long.valueOf(size).floatValue() / 1000000)));
        localDialogIcon = view.findViewById(R.id.localDialogIcon);
        MyRoundedImageView localDialogIcon = view.findViewById(R.id.localDialogIcon);//歌手
        localDialogIcon.setImageBitmap(bitmap);

        // 删除本地歌曲
        TextView delete_view = view.findViewById(R.id.local_delete);
        delete_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File music_file = new File(p);
                File pic_file = new File(picPath);
                if (music_file.delete() && pic_file.delete()) {
                    Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                }
                downloadMusicDao.deleteDownloadMusicByNameAndSinger(song, singer);
                if (starredSongDao.getStarredSongByNameAndSinger(song, singer) != null)
                    starredSongDao.updateByNameAndSinger(song, singer, "http://www.1.com");
                Intent backmain = new Intent(getActivity(), LocalMusicActivity.class);
                getActivity().startActivity(backmain);
                getActivity().finish();
            }
        });

        bottomSheetDialog = new BottomSheetDialog(getActivity());
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置BottomSheetDialog圆角
        bottomSheetDialog.show();
    }

}